package eu.ydp.mathplayer.editor.controller.mathml;

public abstract class MathMLTasksProcessor {

	public static String postprocess(String input){
		while (input.indexOf("</mn><mn>") != -1)
			input = input.replace("</mn><mn>", "");
		while (input.indexOf("</ms><ms>") != -1)
			input = input.replace("</ms><ms>", "");
		
		return input;
	}
	
	public static String preprocess(String input){
		
		input = splitNodes(input, "mn");
		input = splitNodes(input, "ms");
		
		return input;
	}
	
	private static String splitNodes(String input, String nodeName){

		int fromIndex = 0;
		int currIndex;
		while ((currIndex = input.indexOf("<"+nodeName+">", fromIndex)) != -1){
			int closeIndex = input.indexOf("</"+nodeName+">", currIndex);
			int charactersCount = closeIndex - (currIndex + 4);
			String content = input.substring(currIndex+4, closeIndex);
			String newContent = content.substring(0, 1);
			for (int i = 1 ; i < charactersCount ; i ++){
				newContent += "</"+nodeName+"><"+nodeName+">";
				newContent += content.substring(i, i+1);
			}
			input = input.substring(0, currIndex+4) + newContent + input.substring(closeIndex, input.length());
			fromIndex = closeIndex + newContent.length() - content.length();
		}
		
		return input;
	}
}
